package com.atguigu.tingshu.user.strategy.impl;

import com.atguigu.tingshu.album.client.TrackInfoFeignClient;
import com.atguigu.tingshu.common.result.Result;
import com.atguigu.tingshu.model.album.TrackInfo;
import com.atguigu.tingshu.model.user.UserPaidAlbum;
import com.atguigu.tingshu.model.user.UserPaidTrack;
import com.atguigu.tingshu.user.mapper.UserPaidAlbumMapper;
import com.atguigu.tingshu.user.mapper.UserPaidTrackMapper;
import com.atguigu.tingshu.user.service.UserPaidTrackService;
import com.atguigu.tingshu.user.strategy.PurchaseStrategy;
import com.atguigu.tingshu.vo.user.UserPaidRecordVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Assert;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * ClassName: AlbumPurchaseStrategy
 * Package: com.atguigu.tingshu.user.strategy.impl
 * Description:
 *
 * @Author:
 * @Create: 2025/8/9 - 23:38
 * @Version: v1.0
 */

@Service("1002")
@Slf4j
public class TrackPurchaseStrategy implements PurchaseStrategy {

    @Resource
    private UserPaidTrackMapper userPaidTrackMapper;

    @Resource
    private TrackInfoFeignClient trackInfoFeignClient;

    @Resource
    private UserPaidTrackService userPaidTrackService;

    @Override
    public void purchase(UserPaidRecordVo userPaidRecordVo) {
        //防止重复消费
        LambdaQueryWrapper<UserPaidTrack> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UserPaidTrack::getOrderNo, userPaidRecordVo.getOrderNo());
        Long count = userPaidTrackMapper.selectCount(queryWrapper);
        if (count > 0) {
            log.info("当前声音列表有购买过的");
            return;
        }
        //获取到声音的详情，
        Result<TrackInfo> trackInfoResult = trackInfoFeignClient.getTrackInfo(userPaidRecordVo.getItemIdList().get(0));
        Assert.notNull(trackInfoResult, "专辑结果集不能为空");
        TrackInfo trackInfo = trackInfoResult.getData();
        Assert.notNull(trackInfo, "专辑不能为空");
        List<UserPaidTrack> userPaidTrackList = userPaidRecordVo.getItemIdList().stream().map(itemId -> {
            UserPaidTrack userPaidTrack = new UserPaidTrack();
            userPaidTrack.setUserId(userPaidRecordVo.getUserId());
            userPaidTrack.setAlbumId(trackInfo.getAlbumId());
            userPaidTrack.setTrackId(itemId);
            userPaidTrack.setOrderNo(userPaidRecordVo.getOrderNo());
            return userPaidTrack;
        }).collect(Collectors.toList());
        userPaidTrackService.saveBatch(userPaidTrackList);
    }
}
